'use strict';

var core = require('@tauri-apps/api/core');

class SqliteDatabase {
    constructor(path, table) {
        this.columns = [];
        this.path = path;
        this.isOpen = false;
        this.table = table;
    }
    filter(filter) {
        const result = [];
        const reg = /(\w+)\s*=\s*['"]?(.*?)['"]?/g;
        let match;
        while ((match = reg.exec(filter)) !== null) {
            result.push(match[1]);
        }
        return result.filter(item => !this.columns.includes(item)).length <= 0;
    }
    async open() {
        if (this.isOpen)
            return false;
        await core.invoke("plugin:sqlite|open", { path: this.path });
        this.isOpen = true;
        return true;
    }
    async close() {
        if (!this.isOpen)
            return false;
        await core.invoke("plugin:sqlite|close", { path: this.path });
        this.isOpen = false;
        return true;
    }
    async getColumns() {
        if (!this.isOpen)
            return;
        this.columns = await core.invoke("plugin:sqlite|get_columns", { path: this.path, table: this.table });
    }
    async execute(sql) {
        if (!this.isOpen)
            return -1;
        return core.invoke("plugin:sqlite|execute", { path: this.path, sql: sql });
    }
    async query(filter = '', columns = []) {
        if (this.columns.length === 0) {
            await this.getColumns();
        }
        if (filter !== '' && !this.filter(filter))
            return ['error'];
        if (!this.isOpen)
            return ['error'];
        return core.invoke("plugin:sqlite|query", { path: this.path, table: this.table, filter: filter, columns: columns });
    }
    async insert(data) {
        if (this.columns.length === 0) {
            await this.getColumns();
        }
        const keys = Object.keys(data);
        if (keys.filter(item => !this.columns.includes(item)).length > 0)
            return -1;
        if (!this.isOpen)
            return -2;
        return core.invoke("plugin:sqlite|insert", { path: this.path, table: this.table, data: data });
    }
    async update(data, filter = '') {
        if (this.columns.length === 0) {
            await this.getColumns();
        }
        if (filter !== '' && !this.filter(filter))
            return -2;
        if (!this.isOpen)
            return -1;
        return core.invoke("plugin:sqlite|update", { path: this.path, table: this.table, data: data, filter: filter });
    }
    async delete(filter = '') {
        if (this.columns.length === 0) {
            await this.getColumns();
        }
        if (filter !== '' && !this.filter(filter))
            return -2;
        if (!this.isOpen)
            return -1;
        return core.invoke("plugin:sqlite|delete", { path: this.path, table: this.table, filter: filter });
    }
}

exports.SqliteDatabase = SqliteDatabase;
